package com.baidunewmusic;

import java.io.IOException;

import com.baidunewmusic.Playlist.Song;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity {

	private Gallery g;
	private MediaPlayer mp;
	private String playingURL;
	private int location = -1;
	private Song mSong;

	private static final int GET_LYRICS = 1;
	private static final int PLAY_MUSIC = 2;
	private static final int APP_ID = 1239645;

	private NotificationManager mNotificationManager;
	private Notification notification;

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mp.stop();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	@Override
	protected void onStart() {
		super.onStart();
		g.setSelection(location);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final Playlist p = Playlist.getInstance();
		p.load();

		MenuIconAdapter adapter = new MenuIconAdapter(getBaseContext(), p
				.getSongs());
		// Reference the Gallery view
		g = (Gallery) findViewById(R.id.gallery);
		// Set the adapter to our custom adapter (below)
		g.setAdapter(adapter);

		g.setSelection(0);
		if (mp == null)
			mp = new MediaPlayer();

		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mp.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
		mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				final int pos = g.getSelectedItemPosition() + 1;
				if (pos <= g.getCount())
					g.setSelection(pos);
			}
		});
		g.setCallbackDuringFling(false);

		g.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					final int position, long arg3) {

				final Song s = (Song) (parent.getAdapter().getItem(position));

				new Thread() {

					@Override
					public void run() {

						super.run();
						String lyrics = Playlist.getPageSource(s.lyrics);
						if (null != lyrics) {
							lyrics = lyrics.replace("\r\n", "\n");
						}

						Message msg = new Message();
						msg.what = GET_LYRICS;
						msg.obj = lyrics;
						mHandler.sendMessage(msg);
						Message msg2 = new Message();
						msg2.what = PLAY_MUSIC;
						msg2.obj = s;
						location = position;
						mHandler.sendMessage(msg2);
					}

				}.start();

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}

		});

		g.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Song s = (Song) (parent.getAdapter().getItem(position));
				playAudio(s.url);
			}

		});

	}

	private void playAudio(String link) {

		if (mp.isPlaying() && link == playingURL) {
			mp.pause();
			return;
		}

		try {
			mp.reset();
			String path = Playlist.BAIDU_URL + Playlist.getPageSource(link);
			mp.setDataSource(path);
			mp.prepare();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mp.start();
		playingURL = link;
		
		Context context = getApplicationContext(); // application Context
		CharSequence contentTitle = mSong.title; // expanded message title
		CharSequence contentText = mSong.artist; // expanded message text

		int icon = R.drawable.icon;
		CharSequence tickerText = mSong.title + " -- " + mSong.artist;
		long when = System.currentTimeMillis();

		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);

		notification = new Notification(icon, tickerText, when);
		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentIntent);

		mNotificationManager.notify(APP_ID, notification);

	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case GET_LYRICS:
				((TextView) findViewById(R.id.lyrics))
						.setText((String) msg.obj);
				break;
			case PLAY_MUSIC:
				mSong = (Song) msg.obj;
				playAudio(mSong.url);
				break;

			}
		}
	};

}